package cn.itcast.netty.c2;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;

import java.nio.charset.Charset;

public class EchoServer {
    public static void main(String[] args) throws InterruptedException {
        new ServerBootstrap()
                .group(new NioEventLoopGroup())
                .channel(NioServerSocketChannel.class)
                .childHandler(new ChannelInitializer<NioSocketChannel>() {
                    @Override
                    protected void initChannel(NioSocketChannel ch) throws Exception {
                        ch.pipeline().addLast(new ChannelInboundHandlerAdapter() {
                            @Override
                            public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
                                try {
                                    ByteBuf buffer = (ByteBuf) msg;
                                    System.out.println("Server received: " + buffer.toString(Charset.defaultCharset()));

                                    // 创建响应并使用相同的消息内容
                                    ByteBuf reponse = ctx.alloc().buffer();
                                    reponse.writeBytes(buffer);
                                    ctx.writeAndFlush(reponse);

                                    // 注意：这里不需要手动释放buffer，因为Netty会在pipeline处理完成后自动释放
                                } catch (Exception e) {
                                    e.printStackTrace();
                                    ctx.close();
                                }
                            }

                            @Override
                            public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
                                cause.printStackTrace();
                                ctx.close();
                            }
                        });
                    }
                }).bind(8080).sync().channel().closeFuture().sync();
    }
}
